#include "cm.h"
#include <fcntl.h>
#include "dp.h"

#define FIFO_NAME "my_fifo"
#define FIFO_NAME1 "my_fifo1"

int z = 0;

void* rec(void *arg) {
    int *a = (int *)arg;

    int fifo_fd, fifo_fd1;
    char buffer[1024],buffer1[1024];

    // 打开管道（读模式）
    fifo_fd = open(FIFO_NAME, O_RDONLY);
    fifo_fd1 = open(FIFO_NAME1, O_RDONLY);
    
    if (fifo_fd == -1) {
        perror("open");
        exit(1);
    }

    // 从管道读取数据
    read(fifo_fd, buffer, sizeof(buffer) - 1);
    buffer[strcspn(buffer, "\n")] = '\0';  // 去掉换行符
    read(fifo_fd1, buffer1, sizeof(buffer) - 1);
    buffer[strcspn(buffer1, "\n")] = '\0';  // 去掉换行符

    // 关闭管道
    close(fifo_fd);
    close(fifo_fd1);

    // 删除管道文件
    unlink(FIFO_NAME);
    unlink(FIFO_NAME1);

    printf("Program B received: %d\n", atoi(buffer));

    switch (atoi(buffer)){
        case 1:
            printf("This is program 1\n");
            z = atoi(buffer1);
            printf("z = %d\t a = %d\n",z,*a);

            pthread_t pid;
            pthread_create(&pid, NULL, rec_from_cm, (void*)&z);
            pthread_join(pid, NULL);

            break;
        case 2:
            printf("message is program 2\n");
            break;
        default:
            break;
    }

    return NULL;
}